//
//  TallyViewController.m
//  Exam13-2b
//
//  Created by 孙晓晔 on 2017/4/29.
//  Copyright © 2017年 孙晓晔. All rights reserved.
//

#import "TallyViewController.h"
#import <sqlite3.h>
#import "AddTallyViewController.h"
#import "Tally.h"
#import "TimeLineView.h"

@interface TallyViewController ()<AddTallyDelegate>
@property(nonatomic,strong) UIScrollView *scrollView; // 滚动视图

@property (weak, nonatomic) IBOutlet UILabel *incomeLabel; // 收入
@property (weak, nonatomic) IBOutlet UILabel *expenseLabel; // 支出

@property(nonatomic,assign) CGFloat allDateAllLine; // 时光视图高度
@property(nonatomic,strong) NSMutableArray *tallyArr; // 数据
@end

@implementation TallyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.view addSubview:self.scrollView];
    
    [self setUp];
}

// 新增按钮
- (IBAction)add:(id)sender {
    AddTallyViewController *add = [[AddTallyViewController alloc] init];
    add.tallyDelegate = self;
    
    [self.navigationController pushViewController:add animated:YES];
}

// 懒加载
-(UIScrollView *)scrollView {
    if (_scrollView == nil) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64+80, self.view.frame.size.width, self.view.frame.size.height-64-80)];
        
        _scrollView.backgroundColor = [UIColor whiteColor];
    }
    
    return _scrollView;
}

// 懒加载
-(NSMutableArray *)tallyArr {
    if (_tallyArr == nil) {
        
        NSMutableArray *arr = [NSMutableArray array];
        
        sqlite3 *db = [self openDb];
        
        char *sql = "SELECT * FROM tally ORDER BY id DESC";
        sqlite3_stmt *stmt = NULL;
        
        int ret = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
        if (ret == SQLITE_OK) {
            NSLog(@"执行SQL查询语句成功。", nil);
            
            while (sqlite3_step(stmt) == SQLITE_ROW) {
                
                int uid = sqlite3_column_int(stmt, 0);
                char *type = (char*)sqlite3_column_text(stmt, 1);
                int icon = sqlite3_column_int(stmt, 2);
                char *money = (char*)sqlite3_column_text(stmt, 3);
                char *createtime = (char*)sqlite3_column_text(stmt, 5);
                
                Tally *tally = [[Tally alloc]init];
                tally.uid = uid;
                
                tally.type = [NSString stringWithUTF8String:type];
                tally.icon = icon;
                tally.money = [[NSString stringWithUTF8String:money] doubleValue];
                
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                tally.createTime = [dateFormatter dateFromString:[NSString stringWithUTF8String:createtime]];
                
                [arr addObject:tally];
            }
        } else {
            NSLog(@"执行SQL查询语句失败。错误码 = %d" , ret);
        }
        
        sqlite3_finalize(stmt);
        
        [self closeDb:db];
        
        _tallyArr = arr;
    }
    
    return _tallyArr;
}

// 新增信息
- (void)addTally:(Tally *)tally {
    NSLog(@"add tally", nil);
    
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"insert into tally(type, icon, money, createTime) values('%@','%ld','%f', datetime(CURRENT_TIMESTAMP, 'localtime'))", tally.type, tally.icon, tally.money];
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"添加SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
    
    self.tallyArr = nil;
}

// 编辑信息
-(void)editTally:(Tally *)tally {
    AddTallyViewController *add = [[AddTallyViewController alloc] init];
    add.tallyDelegate = self;
    
    [add selectTally:tally];
    
    [self.navigationController pushViewController:add animated:YES];
}

// 更新信息
- (void)updateTally:(Tally *)tally {
    NSLog(@"edit tally.", nil);
    
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"update tally set money = '%f' where id = %ld", tally.money, tally.uid];
    
    NSLog(str, nil);
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"更新SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
    
    self.tallyArr = nil;
}

// 删除信息
- (void)deleteTally:(Tally *)tally {
    NSLog(@"delete tally.", nil);
    
    sqlite3 *db = [self openDb];
    
    NSString *str = [NSString stringWithFormat:@"delete from tally where id = %ld", tally.uid];
    
    NSLog(str, nil);
    
    const char *sql = [str UTF8String];
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"删除SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
    
    self.tallyArr = nil;
    
    [self showTimeLineView];
}

// 创建表结构
-(void)setUp {
    const char *sql = "create table if not exists tally(id integer primary key autoincrement, type varchar, icon integer, money real, content varchar, createtime DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')))";
    
    sqlite3 *db = [self openDb];
    
    char *err;
    
    int ret = sqlite3_exec(db, sql, NULL, NULL, &err);
    if (ret == SQLITE_OK) {
        NSLog(@"执行SQL语句成功。", nil);
    } else {
        NSLog(@"执行SQL语句失败。错误码 = %d" , ret);
    }
    
    [self closeDb:db];
}

// 打开数据库
-(sqlite3*)openDb {
    const char *filename = [[self path] UTF8String];
    
    sqlite3 *db = NULL;
    
    int ret = sqlite3_open(filename, &db);
    
    if (ret == SQLITE_OK) {
        NSLog(@"打开数据库成功。", nil);
    } else {
        NSLog(@"打开数据库失败。错误码 = %d" , ret);
    }
    
    return db;
}

// 关闭数据库
-(void)closeDb:(sqlite3*)db {
    int ret = sqlite3_close(db);
    if (ret == SQLITE_OK) {
        NSLog(@"关闭数据库成功。", nil);
    } else {
        NSLog(@"关闭数据库失败。错误码 = %d" , ret);
    }
}

// 设置数据库文件
-(NSString*)path {
    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *strDoc = [arr firstObject];
    
    NSLog(strDoc, nil);
    
    return [NSString stringWithFormat:@"%@/sqlite.db", strDoc];
}

-(void)viewWillAppear:(BOOL)animated {
    [self showTimeLineView];
}

// 显示数据
-(void)showTimeLineView {
    
    double income = 0, expense = 0;
    
    self.allDateAllLine = 0;
    for (Tally *tally in self.tallyArr) {
//        NSLog(@"uid = %ld, icon = %ld, type = %@, money = %.2f", tally.uid, tally.icon, tally.type, tally.money);
        
        self.allDateAllLine += kLineHeight + kBtnWidth;
        
        if ([tally.type isEqualToString:@"1"]) {
            income += tally.money;
        } else {
            expense += tally.money;
        }
    }
    
    NSLog(@"allDateAllLine = %.f", self.allDateAllLine);
    
    self.incomeLabel.text = [NSString stringWithFormat:@"%.2f", income];
    self.expenseLabel.text = [NSString stringWithFormat:@"%.2f", expense];
    
    self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.allDateAllLine + 20);
    
    [self timeLineView:self.allDateAllLine];
    
    [self.scrollView setContentOffset:CGPointZero animated:YES];
}

// 添加时光视图
-(void)timeLineView:(CGFloat)height {
    CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, height);
    
    TimeLineView *view = [[TimeLineView alloc]initWithFrame:rect];
    view.delegate = self;
    view.tag = 100;
    view.backgroundColor = [UIColor whiteColor];
    view.tallyArr = self.tallyArr;
    
    [self.scrollView addSubview:view];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
